package com.khalil.kkadmin.system.menu;

import com.khalil.kkadmin.common.util.TreeUtil;
import com.khalil.kkadmin.infrastructure.jpa.domain.TreeEntityBase;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

@Service
public class SysMenuService {
    private final SysMenuRepository sysMenuRepository;

    public SysMenuService(SysMenuRepository sysMenuRepository) {
        this.sysMenuRepository = sysMenuRepository;
    }

    public List<SysMenu> getTree() {
        List<SysMenu> sysMenus = sysMenuRepository.findAll();
        List<SysMenu> sysMenuTreeList = TreeUtil.buildTree(sysMenus, (menu) -> menu.getParentId() == null);
        TreeUtil.sortTree(sysMenuTreeList, Comparator.comparingInt(TreeEntityBase::getOrderNum));
        return sysMenuTreeList;
    }

    public SysMenu get(Integer id) {
        return sysMenuRepository.findById(id).orElse(null);
    }

    public List<SysMenu> getUserMenus(String username) {
        return sysMenuRepository.findAll();
    }

    public SysMenu saveOrUpdate(SysMenu sysMenu) {
        return sysMenuRepository.save(sysMenu);
    }

    public void delete(Integer id) {
        sysMenuRepository.deleteById(id);
    }
}
